package Servlet;

import pojo.Flight;
import service.FlightService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

@WebServlet("/updateFlightServlet")
public class UpdateFlightServlet extends HttpServlet {

    private FlightService flightService = new FlightService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理POST请求的乱码问题
        request.setCharacterEncoding("utf-8");

        //1. 接收表单提交的数据，封装为一个Flight对象
        String flightId = request.getParameter("flightId");
        String flyId = request.getParameter("flyId");
        String flyDesc = request.getParameter("flyDesc");
        String destination = request.getParameter("destination");
        String flyTime = request.getParameter("flyTime");

        //封装为一个Flight对象
        Flight flight = new Flight();
        flight.setId(Integer.valueOf(flightId));
        flight.setFlyId(flyId);
        flight.setFlyDesc(flyDesc);
        flight.setDestination(destination);

        if(flyTime!=null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                flight.setFlyTime(sdf.parse(flyTime));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }

        //2. 调用service 完成修改
        flightService.updateFlight(flight);

        //3. 转发到查询所有Servlet
        request.getRequestDispatcher("/selectFlightServlet").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        this.doGet(request, response);
    }
}